package servlet.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class SimpleFilter implements Filter {

	private String charset = "utf-8";
    public SimpleFilter() {
    	
    }
    
    public void init(FilterConfig fConfig) throws ServletException {
    	System.out.println("** init过滤器初始化");
    	String author = fConfig.getInitParameter("author");
    	charset = fConfig.getInitParameter("charset");
    	
    	System.out.println("author:" + author);
    	System.out.println("charset:" + charset);
    }

	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
		System.out.println("** 执行doFilter之前");
		request.setCharacterEncoding(charset);
		
		HttpServletRequest httpReq =  (HttpServletRequest)request;
		HttpServletResponse httpRes =  (HttpServletResponse)response;
		httpRes.setCharacterEncoding("UTF-8");
		httpRes.setHeader("content-type","text/html;charset=UTF-8");
		
		if (httpReq.getSession().getAttribute("userId") != null) {
			chain.doFilter(request, response);
		} else {
			chain.doFilter(request, response);
		}
		
		System.out.println("** 执行doFilter之后");
	}
	
	public void destroy() {
		System.out.println("** 销毁destroy");
		
	}

}
